package com.kk.loadimg;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * 接收图片
 *
 * @author 王志强
 * @date 2021-12-02
 */
public class ImgServer {
    public ImgServer() {
        try {
            //建立连接
            ServerSocket serverSocket = new ServerSocket(8888);

            while (true) {
                Socket socket = serverSocket.accept();

                //输入流
                InputStream inputStream = socket.getInputStream();

                //文件输出流，输出到具体的文件
                FileOutputStream fileOutputStream = new FileOutputStream(new File("receiveImg.jpg"));

                byte[] buff = new byte[512];
                int len;

                //读多少，写多少
                while ((len = inputStream.read(buff)) != -1) {
                    fileOutputStream.write(buff, 0, len);
                }
                fileOutputStream.flush();

                System.out.println("成功接收！！");
/*                //服务端 响应 客户端结果
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("up over!".getBytes(StandardCharsets.UTF_8));
                socket.close();*/

            }
        } catch (IOException e) {
            System.out.println("连接断开");
        }
    }

    public static void main(String[] args) {
        ImgServer imgServer = new ImgServer();
    }
}
